<?php
declare (strict_types = 1);

namespace app\middleware\Admin;

use app\admin\model\Admins;
use app\middleware\BaseMiddleware;
use think\facade\Session;

class RabcMiddleware extends BaseMiddleware
{
    use \liliuwei\think\Jump;

    // 过滤的路由：不进行检测的路由
    protected $filter_route = [
        'indexs/profile', // 登录管理员的个人资料
        'indexs/setPassword', // 登录管理员的密码设置
        'uploads/file', // 图片上传
    ];

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $route = $request->controller(true) . '/' . $request->action();

        /**
         * 开启了路由验证
         */
        if (!$this->checkRabc($route)){
            if ($request->isPost()){
                return $this->errorJson('无权限', -2);
            }else{
                return $this->error('无权限');
            }
        }

        return $next($request);
    }

    private function checkRabc(string $route):bool
    {
        // 只要路由不再过滤路由属性值中，那么就自动记录日志
        if ( isset(array_flip($this->filter_route)[$route]) ) {
            return true;
        }
        if ($admin = getLoginAdmin()){
            if ($menus = Admins::getInstance()->detail($admin->admin_id)->role->menus->toArray()){
                $routes = array_flip(array_column($menus, 'menu_url'));
                if (array_key_exists($route, $routes)){
                    return true;
                }
            }
        }
        return false;
    }
}
